#!/usr/bin/env python
# coding=utf-8

import requests
# from bs4 import BeautifulSoup
import json
import re

# 'ascii' codec can't encode characters
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class BaiduMusicDownload(object):

    def __init__(self):
        self.__BASE_URL = r'http://music.baidu.com/search?key='
        self.__SONG_DATA_URL = r'http://music.baidu.com/data/music/fmlink?songIds='
        self.__SONG_SEARCH_URL = None
        self.__SONG_REAL_DATA = None
        self.__SONG_REAL_URL = None

        # Song info
        self.__SONG_ID = None
        self.__SONG_NAME = None
        self.__SONG_AUTHOR = None
        self.__SONG_FORMAT = None
        self.__SONG_ALBUM = None

    def get_song_id(self, songName):
        self.__SONG_SEARCH_URL = self.__BASE_URL + str(songName)

        req = requests.get(self.__SONG_SEARCH_URL)
        # song = BeautifulSoup(req.content)
        song = req.content

        song_id_all = re.findall(r'<a href="/song/([^"]+)"', str(song))

        if len(song_id_all) == 0:
            return False
        
        self.__SONG_ID = song_id_all[0]
        return song_id_all[0]

    def get_real_song_data(self):
        data_url = self.__SONG_DATA_URL+str(self.__SONG_ID)
        req = requests.get(data_url)

        song_data = json.loads(str(req.content))['data']
        if song_data != '':
            songList = song_data['songList'][0]
            self.__SONG_NAME = songList['songName']
            self.__SONG_AUTHOR = songList['artistName']
            self.__SONG_FORMAT = songList['format']
            self.__SONG_ALBUM = songList['albumName']
            self.__SONG_REAL_URL = songList['songLink']
        
        self.__SONG_REAL_DATA = song_data
        return self.__SONG_REAL_DATA
            
    def download_song(self, songName):
        # Cannot Find Or download This song
        if self.get_song_id(songName) == False:
            return False

        self.get_real_song_data()

        req = requests.get(self.__SONG_REAL_URL)

        mp3Name = "{songName}--{author}<<{album}>>.{format}".format(
            songName = self.__SONG_NAME,
            author = self.__SONG_AUTHOR,
            format = self.__SONG_FORMAT,
            album = self.__SONG_ALBUM
            )
        mp3file = open(mp3Name, 'wb')
        mp3file.write(req.content)
        mp3file.close()

        print mp3Name

        return mp3Name

    def get_real_song_url(self):
        return self.__SONG_REAL_URL

    def get_song_name(self):
        return self.__SONG_NAME

    def get_song_author(self):
        return self.__SONG_AUTHOR

    def get_song_album(self):
        return self.__SONG_ALBUM


if __name__ == '__main__':
    import sys
    
    if len(sys.argv) == 1:
        print "Usage:"
        print "\t{filename} SongName".format(filename=sys.argv[0])
        print "\t{filename} songName1 songName2 ...".format(filename=sys.argv[0])
        exit(False)

    download = BaiduMusicDownload()
    for song in sys.argv:
        if song == sys.argv[0]:
            continue
        download.download_song(song)
